<?php
/**
 * BugFree is free software under the terms of the FreeBSD License.
 *
 * list changes.
 *
 * @link        http://www.bugfree.org.cn
 * @package     BugFree
 */
/* Init BugFree system. */
require('Include/Init.inc.php');
require('Include/FuncImportOutport.php');
@ini_set('memory_limit', -1);

// the flag of using custom field
$hasCustomField = true;
$ProjectID = testGetCurrentProjectId();
if($_GET['ProjectID'] - 0 > 0)
{
    $_SESSION['ChangeQueryCondition'] = "ProjectID = '{$_GET['ProjectID']}'";
}


if($_GET['ModuleID'] - 0 > 0)
{
    $_SESSION['TestCurrentModuleID'] = $_GET['ModuleID'];
    $_SESSION['ChangeQueryCondition'] = "ModuleID IN ({$_GET['ChildModuleIDs']})";
}

if($_GET['ActionType']=='FromNotifyEmail')
{
      $TopModuleID = $_GET['TopModuleID'];
      $ChildModuleList = testGetProjectModuleList($_GET['ProjectID'], 'Bug');//获取所有Module，以及父子关
      $ChildModules = $ChildModuleList[$TopModuleID]['ChildIDs'];//获得当前Module的所有子Module
      if($TopModuleID>=0)
      {
         $_SESSION['ChangeQueryCondition'] = str_replace("\'", "'", $_GET['Condition'])." AND ProjectID={$_GET[ProjectID]} AND ModuleID in({$ChildModules})";
      }
      else
      {
         $_SESSION['ChangeQueryCondition'] = str_replace("\'", "'", $_GET['Condition'])." AND ProjectID={$_GET[ProjectID]}";
      }
      $_SESSION['TestMode'] ='Change';
}

if($_POST['PostQuery'])
{
    $hasCustomField = false;
    $_SESSION['hasChangeCustomField'] = false;
    $QueryStr = baseGetGroupQueryStr($_POST);
    $_SESSION['ChangeQueryCondition'] = $QueryStr;
    $_SESSION['ChangeQueryTitle'] = '';
    $_SESSION['ChangeAndOrListCondition'] = baseGetAndOrListStr($_POST);
    $_SESSION['ChangeFieldListCondition'] = baseGetFieldListStr($_POST);
    $_SESSION['ChangeOperatorListCondition'] = baseGetOperatorListStr($_POST);
    $_SESSION['ChangeValueListCondition'] = baseGetValueListStr($_POST);
    $_SESSION['ChangeLeftParenthesesListCondition'] = baseGetLeftParentheseListStr($_POST);
    $_SESSION['ChangeRightParenthesesListCondition'] = baseGetRightParentheseListStr($_POST);
    $arr = array_diff($_SESSION['ChangeFieldListCondition'], array_keys($_LANG['ChangeQueryField']));
    if(!empty($arr))
    {
        $hasCustomField = $_SESSION['hasChangeCustomField']= true;
    }
    unset($arr);
}

if($_REQUEST['QueryID'])
{
    $hasCustomField = false;
    $_SESSION['hasChangeCustomField'] = false;
    $QueryInfo = dbGetRow('TestUserQuery', '', "QueryID='{$_REQUEST[QueryID]}' AND QueryType='Change'");
    $_SESSION['ChangeQueryCondition'] = $QueryInfo['QueryString'];
    $_SESSION['ChangeQueryTitle'] = $QueryInfo['QueryTitle'];
    $_SESSION['ChangeAndOrListCondition'] = unserialize($QueryInfo['AndOrList']);
    $_SESSION['ChangeFieldListCondition'] = unserialize($QueryInfo['FieldList']);
    $_SESSION['ChangeOperatorListCondition'] = unserialize($QueryInfo['OperatorList']);
    $_SESSION['ChangeValueListCondition'] = unserialize($QueryInfo['ValueList']);
    $_SESSION['ChangeFieldsToShow'] = $QueryInfo['FieldsToShow'];
    $_SESSION['ChangeLeftParenthesesListCondition'] = unserialize($QueryInfo['LeftParentheses']);
    $_SESSION['ChangeRightParenthesesListCondition'] = unserialize($QueryInfo['RightParentheses']);
    $arr = array_diff($_SESSION['ChangeFieldListCondition'], array_keys($_LANG['ChangeQueryField']));
    if(!empty($arr))
    {
        $hasCustomField = $_SESSION['hasChangeCustomField']= true;
    }
    unset($arr);
}
else
{
   $_REQUEST['QueryID'] = '-1';
}

$WHERE = array();
$URL = array();

$WHERE[] = $_SESSION['TestUserACLSQL'];

if($_SESSION['ChangeQueryCondition'] != '')
{
    $WHERE[] = $_SESSION['ChangeQueryCondition'];
}

if($_GET['OrderBy'])
{
    $OrderByList = explode('|', $_GET['OrderBy']);
    $OrderByColumn = $OrderByList[0];
    $OrderByType = $OrderByList[1];
    $OrderBy = join(' ', $OrderByList);
    $URL[] = 'OrderBy=' . $_GET['OrderBy'];
    $_SESSION['ChangeOrderBy']['OrderBy'] = $OrderBy;
    $_SESSION['ChangeOrderBy']['OrderByColumn'] = $OrderByColumn;
    $_SESSION['ChangeOrderBy']['OrderByType'] = $OrderByType;
}
else
{
    if(empty($_SESSION['ChangeOrderBy']))
    {
        $_SESSION['ChangeOrderBy']['OrderBy'] = ' ChangeID DESC';
        $_SESSION['ChangeOrderBy']['OrderByColumn'] = 'ChangeID';
        $_SESSION['ChangeOrderBy']['OrderByType'] = 'DESC';
    }
    $OrderBy = $_SESSION['ChangeOrderBy']['OrderBy'];
    $OrderByColumn = $_SESSION['ChangeOrderBy']['OrderByColumn'];
    $OrderByType = $_SESSION['ChangeOrderBy']['OrderByType'];
}

if($_GET['QueryMode'])
{
    $hasCustomField = false;
    $_SESSION['hasChangeCustomField'] = false;
    $QueryModeList = explode('|', $_GET['QueryMode']);
    $QueryColumn = $QueryModeList[0];
    $QueryValue = $QueryModeList[1];
    $WHERE = array();
    $WHERE[] = $_SESSION['TestUserACLSQL'];
    $QueryCondition = "";
    if(preg_match('/date/i', $QueryColumn))
    {
        $QueryCondition =  $QueryColumn . ' ' . sysStrToDateSql($QueryValue);
    }
    else
    {
        $QueryCondition = "{$QueryColumn}='{$QueryValue}'";
    }
    $_SESSION['ChangeQueryCondition'] = $QueryCondition;
    $_SESSION['ChangeQueryColumn'] = $QueryColumn;
    $WHERE[] = $QueryCondition;
    $URL[] = 'QueryMode=' . sysStripSlash($_GET['QueryMode']);
    // check if is set custom field for special function
    if(!array_key_exists($QueryColumn, $_LANG['ChangeQueryField']))
    {
        $hasCustomField = $_SESSION['hasChangeCustomField'] = true;
    }
}
$Url = '?' . join('&', $URL);
$WHERE[] = "IsDroped = '0'";
$Where = join(' AND ', $WHERE);

if(isset($_SESSION['hasChangeCustomField']))
{
    $hasCustomField = $_SESSION['hasChangeCustomField'];
}
$FieldsToShow = testSetCustomFields('Change', $ProjectID, $hasCustomField);
if(!array_key_exists($OrderByColumn, $FieldsToShow))
{
    $OrderBy = 'ChangeID DESC';
    $OrderByColumn = 'ChangeID';
    $OrderByType = 'DESC';
}

/* Get pagination */
$Pagination = new Page('ChangeInfo', '', '', '', 'WHERE ' . $Where . ' ORDER BY ' . $OrderBy, $Url, $MyDB);
$LimitNum = $Pagination->LimitNum();
$TPL->assign('PaginationDetailInfo', $Pagination->getDetailInfo());
$ColumnArray = @array_keys($FieldsToShow);
$Columns = 'ChangeID,ChangeStatus,' . join(',',$ColumnArray);


$OrderColumnList = $ColumnArray;
$OrderByTypeList = array();
foreach($OrderColumnList as $OrderColumn)
{
    if($OrderColumn == $OrderByColumn)
    {
        $OrderByTypeList[$OrderColumn] = $OrderTypeReverseArray[$OrderByType];
    }
    else
    {
        $OrderByTypeList[$OrderColumn] = $OrderByType;
    }
}

if($_GET['Export'] == 'HtmlTable')
{
    $Columns = '';
    $LimitNum = '';
}

$ChangeListSql = dbGetListSql(dbGetPrefixTableNames('ChangeInfo'), '', $Where, '', $OrderBy, $LimitNum);
if($Where != $_SESSION['OldChangeQueryWhereStr'])
{
    $_SESSION['OldChangeQueryWhereStr'] = $Where;
    if(!($_GET['QueryMode']))
    {
        $_SESSION['ChangeQueryColumn'] = '';
    }
}
if(($ProjectID != null) && ($hasCustomField))
{
    $ProjectInfo = dbGetRow('TestProject', '', "ProjectID='{$ProjectID}'");
    $FieldSet = $ProjectInfo['FieldSet'];
    if(!empty($FieldSet))
    {
        $xml = simplexml_load_string($FieldSet);
        $fields = $xml->xpath('/fieldset/fields[@type="Change"]/field');
        if($fields)
        {
            $tableName = testGetFieldTable('Change', $ProjectID);
            $Pagination = new Page(dbGetPrefixTableNames('ChangeInfo') . ' LEFT JOIN ' . $tableName .' ON ' . dbGetPrefixTableNames('ChangeInfo') . '.ChangeID = ' . $tableName . '.FieldID', '', '', '', 'WHERE ' . $Where . ' ORDER BY ' . $OrderBy, $Url, $MyDB, false);
            $LimitNum = $Pagination->LimitNum();
            $TPL->assign('PaginationDetailInfo', $Pagination->getDetailInfo());
            $Where .= ' AND ProjectID = ' . $ProjectID;
            $sql =  dbGetListSql(dbGetPrefixTableNames('ChangeInfo') . ',' . $tableName, '', $Where, '', $OrderBy, $LimitNum);
            $ChangeListSql = str_replace(dbGetPrefixTableNames('ChangeInfo') . ',' . $tableName, dbGetPrefixTableNames('ChangeInfo') . ' LEFT JOIN ' . $tableName .' ON ' . dbGetPrefixTableNames('ChangeInfo') . '.ChangeID = ' . $tableName . '.FieldID', $sql);
        }
    }
}

$ChangeList = dbGetListBySql($ChangeListSql);
$UserNameList = testGetOneDimUserList();
$ChangeList = testSetChangeListMultiInfo($ChangeList, $UserNameList);
$TPL->assign('ChangeList', $ChangeList);

$TPL->assign('OrderByColumn', $OrderByColumn);
$TPL->assign('OrderByType', $OrderByType);
$TPL->assign('QueryMode', $_GET['QueryMode']);
$TPL->assign('QueryColumn', $_SESSION['ChangeQueryColumn']);
$TPL->assign('OrderByTypeList', $OrderByTypeList);
$TPL->assign('BaseTarget', '_self');
$TPL->assign('TestMode', 'Change');

//ChangeList的导入处理代码
if($_FILES['file']['error']==2)	//导入成功
{
      sysObFlushJs("alert('{$_LANG['ImportFileExceed']}');");
}
elseif($_FILES['file']['error']==0)
{
        if($_FILES['file']['tmp_name'])   // 如果文件存在则进行批量导入
        {
	  				$findtype=strtolower(strrchr($_FILES['file']['name'],"."));

          	if($findtype!='.xml')	//文件必须以.xml结尾
          	{
            		sysObFlushJs("alert('{$_LANG['ImportFileSuffixError']}');");
          	}
          	else 
          	{
          			//读取文件内容到FileContents
		  					$file=fopen($_FILES['file']['tmp_name'],"r");
		  					$FileContents = fread($file, filesize($_FILES['file']['tmp_name']));
		  					//Rainy_Debug($FileContents);
		  					$FileContents = preg_replace('/<Font.*>|<\/Font>/Us', '', $FileContents);
								//将文件内容解析成变量，并存储在Dom变量中	
		            $Dom =  XML_unserialize($FileContents);
    		        $DomRowArray = $Dom[Workbook][Worksheet][Table][Row];
								//解析DomRowArray 并导入至数据库中
            		ParseImportChangeXML($DomRowArray,$_LANG);
        	}
    		}
}


if($_GET['Export'] == 'HtmlTable')
{
    $TPL->assign('DataList', $ChangeList);
    $TPL->assign('FieldsToShow', $_LANG["ChangeFields"]);
    $TPL->display('ExportList.tpl');
    exit;
}

if($_GET['Export'] == 'XMLFile')  //批量导出Change
{
   $ChangeExportList = dbGetList('ChangeInfo','', $Where, '', $OrderBy);
   $ChangeCount = sizeof($ChangeExportList);


   if($ChangeCount >5000 ){
     sysObFlushJs("alert('{$_LANG['ExportCountExceed']}');");
   }
   else{
       $ChangeExportColumnMust = array('ChangeID' , 'ChangeTitle', 'ProjectName', 'ModulePath', 'ReproSteps'); //必须包含的字段

      $ChangeExportColumnArray = $ColumnArray;
      foreach($ChangeExportColumnMust as $Item)
      {
         if(!in_array($Item, $ChangeExportColumnArray))
            $ChangeExportColumnArray[] = $Item;

      }

      $URL=$_CFG['File']['UploadDirectory'] . "/changelist.xml";
      $File = fopen($URL,"w");

      $Content = ExportXML($ChangeExportList,$ChangeExportColumnArray,$_LANG['ChangeFields']);

      file_put_contents($URL, $Content);
      header('Content-type: text/xml; charset=utf-8');
      header('Content-Disposition: attachment; filename=changelist.xml');
      readfile($URL);
      exit;
   }
}
$TPL->assign('TestIsAdmin', $_SESSION['TestIsAdmin']);
$TPL->assign('QueryID', $_REQUEST['QueryID']);
$TPL->assign('QueryTitle', $_SESSION['ChangeQueryTitle'] );
$TPL->display('ChangeList.tpl');
?>